<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="楼栋" prop="buildingName">
                <el-select v-model="queryParams.buildingName" placeholder="请选择楼栋" style="width:200px">
                    <el-option v-for="dict in dict.type.loudong" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="宿舍编号" prop="dormitoryId">
                <el-input v-model="queryParams.dormitoryId" placeholder="请输入宿舍编号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="外包" prop="outsource">
                <el-select v-model="queryParams.outsource" placeholder="请选择是否外包宿舍">
                    <el-option label="是" value="是"></el-option>
                    <el-option label="否" value="否"></el-option>

                </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="employeename">
                <el-input v-model="queryParams.employeename" placeholder="请输入" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="性质" prop="nature">
                <el-select v-model="queryParams.nature" placeholder="请选择" style="width:200px">
                    <el-option key="宿舍" label="宿舍" value="宿舍"></el-option>
                    <el-option key="夫妻" label="夫妻" value="夫妻"></el-option>
                    <el-option key="大学生" label="大学生" value="大学生"></el-option>
                    <el-option key="招待所" label="招待所" value="招待所"></el-option>
                    <el-option key="外包施工" label="外包施工" value="外包施工"></el-option>
                    <el-option key="仓库" label="仓库" value="仓库"></el-option>
                    <el-option key="商铺" label="商铺" value="商铺"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="容量" prop="boolmanyuan">
                <el-select v-model="queryParams.boolmanyuan" placeholder="请选择" style="width:200px">
                    <el-option key="不限" label="不限" value=""></el-option>
                    <el-option key="未满" label="未满" value="未满"></el-option>
                    <el-option key="满员" label="满员" value="满员"></el-option>
                    <el-option key="空房" label="空房" value="空房"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="department">
                <treeselect ref="tree" :options="deptOptions" :show-count="true" style="width: 260px" placeholder="请选择归属部门"
                    @input="treeSelectInput" @select="treeSelectChange" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['business:dormitory:add']">新增</el-button>
                <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['business:dormitory:edit']">修改</el-button>
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['business:dormitory:remove']">删除</el-button> -->
                <!-- <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                    v-hasPermi="['system:dormitory:import']">导入住宿人员</el-button> -->
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['business:dormitory:export']">导出</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="card-container">
            <el-col :span="4" v-for="(item, index) in dormitoryList" :key="index">

                <el-tooltip effect="dark" placement="top" :manual="true" v-model="tooltipStates[index]">
                    <div slot="content">
                        <p>是否外包: {{ item.outsource }}</p>
                        <p>标签: {{ item.mark }}</p>
                        <p>缴费期: {{ item.feeDate }}</p>
                        <p>金额: {{ item.feeAmount }}</p>
                        <p>房租: {{ item.rent }}</p>
                        <p>级别: {{ item.level }}</p>
                        <p>空调费: {{ item.airConditioningFee }}</p>
                        <p>备注: {{ item.remark }}</p>
                    </div>

                    <el-card style="margin-top: 10px;min-height: 300px;" class="card">
                        <div slot="header" >
                            <span>{{ item.buildingName }}{{ item.dormitoryId }}</span>
                            <div style="float: right;">
                                {{ item.gender }}/{{ item.nature }}
                                {{ item.currentCapacity }} / {{ item.capacity }}
                            </div>
                        </div>
                        <div class="card-content">
                            <!-- <p>性别: {{ item.gender }}</p>
                            <p>性质: {{ item.nature }}</p> -->
                            <div v-if="item.children && item.children.length">
                                <p v-for="(child, childIndex) in item.children" :key="childIndex">
                                    <span v-if="child.fullName">{{ child.fullName }} - {{ child.department }} - {{
                                        child.contactNumber }} <el-button size="mini" type="text"
                                            icon="el-icon-remove-outline" @click="handleOutline(child)"
                                            v-hasPermi="['business:dormitory:outline']">退房</el-button></span>
                                    <span v-else style="color: darkgrey;">空床位 <el-button size="mini" type="text"
                                            icon="el-icon-delete" @click="handleDeletebed(child)"
                                            v-hasPermi="['business:dormitory:removebed']">删除</el-button></span>

                                </p>
                            </div>
                        </div>
                        <div class="card-footer">
                            <el-button size="mini" type="success" icon="el-icon-more" circle
                                 @click="toggleTooltip(index)"></el-button>
                            <el-button size="mini" type="success" icon="el-icon-plus" circle
                                v-hasPermi="['business:dormitory:addbed']" @click="handleaddbed(item)"></el-button>
                            <el-button size="mini" type="primary" icon="el-icon-edit" circle
                                v-hasPermi="['business:dormitory:edit']" @click="handleUpdate(item)"></el-button>
                            <el-button size="mini" v-hasPermi="['business:dormitory:remove']" type="danger"
                                icon="el-icon-delete" circle @click="handleDelete(item)"></el-button>
                        </div>

                        <!-- Custom content slot for Tooltip -->

                    </el-card>
                </el-tooltip>



            </el-col>
        </el-row>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" pageSizes="36" />

        <!-- 添加或修改宿舍对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="楼栋名称" prop="buildingName">
                    <el-select v-model="form.buildingName" placeholder="请选择楼栋" style="width:200px">
                        <el-option v-for="dict in dict.type.loudong" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="宿舍编号" prop="dormitoryId">
                    <el-input v-model="form.dormitoryId" placeholder="请输入宿舍编号" style="width:200px" />

                </el-form-item>
                <el-form-item label="楼层" prop="floor">
                    <!-- <el-input v-model="form.floor" placeholder="请输入宿舍编号" style="width:200px" /> -->
                    <el-input-number v-model="form.floor" placeholder="自动计算" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                        <el-radio label="其他">其他</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否外包宿舍" prop="outsource">
                    <el-radio-group v-model="form.outsource">
                        <el-radio label="否">否</el-radio>
                        <el-radio label="是">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="容纳人数" prop="capacity">
                    <el-input-number v-model="form.capacity" placeholder="请输入容纳人数" />
                </el-form-item>
                <el-form-item label="性质" prop="nature">
                    <el-select v-model="form.nature" placeholder="请选择" style="width:200px">
                        <el-option key="宿舍" label="宿舍" value="宿舍"></el-option>
                        <el-option key="夫妻" label="夫妻" value="夫妻"></el-option>
                        <el-option key="大学生" label="大学生" value="大学生"></el-option>
                        <el-option key="招待所" label="招待所" value="招待所"></el-option>
                        <el-option key="外包施工" label="外包施工" value="外包施工"></el-option>
                        <el-option key="仓库" label="仓库" value="仓库"></el-option>
                        <el-option key="商铺" label="商铺" value="商铺"></el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="标签" prop="mark">
                    <el-select v-model="form.mark" placeholder="请选择" style="width:200px">

                        <el-option key="空房" label="空房" value="空房"></el-option>
                        <el-option key="满员" label="满员" value="满员"></el-option>
                        <el-option key="未满员" label="未满员" value="未满员"></el-option>
                        <el-option key="单人间" label="单人间" value="单人间"></el-option>
                        <el-option key="双人间" label="双人间" value="双人间"></el-option>
                        <el-option key="四人间" label="四人间" value="四人间"></el-option>
                        <el-option key="八人间" label="八人间" value="八人间"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="缴费期" prop="feeDate">

                    <el-input v-model="form.feeDate" placeholder="请输入缴费日期" />
                </el-form-item>
                <el-form-item label="缴费金额" prop="feeAmount">
                    <el-input v-model="form.feeAmount" placeholder="请输入缴费金额" />
                </el-form-item>
                <el-form-item label="空调费" prop="airConditioningFee">
                    <el-input v-model="form.airConditioningFee" placeholder="请输入空调费" />
                </el-form-item>
                <el-form-item label="级别" prop="level">
                    <el-input v-model="form.level" placeholder="请输入级别" />
                </el-form-item>
                <el-form-item label="房租" prop="rent">
                    <el-input v-model="form.rent" placeholder="请输入房租" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入" />
                </el-form-item>
                <!-- <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入 />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 添加或修改床位对话框 -->
        <el-dialog :title="bedtitle" :visible.sync="bedopen" width="500px" append-to-body>
            <el-form ref="bedform" :model="bedform" label-width="80px">
                <el-form-item label="床位号" prop="bedcode">
                    <el-input v-model="bedform.bedcode" placeholder="请输入床位号" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="bedbuttonLoading" type="primary" @click="submitbedForm">确 定</el-button>
                <el-button @click="bedcancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 数据导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 编辑收费信息对话框 -->
        <el-dialog title="编辑收费信息" :visible.sync="feeopen" width="500px" append-to-body>
            <Fee :rowData="rowData"></Fee>
        </el-dialog>
    </div>
</template>
  
<script>
import { listDormitory, getDormitory, delDormitory, addDormitory, updateDormitory } from "@/api/business/dormitory";
import { listBeds, getBeds, delBeds, addBeds, updateBeds, clearBed } from "@/api/business/beds";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import Fee from "@/views/business/dormitory/fee.vue";
export default {
    name: "Dormitory",
    dicts: ['loudong'],
    components: { Fee, Treeselect },

    data() {
        return {
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 宿舍表格数据
            dormitoryList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 36,
                dormitoryId: undefined,
                buildingNumber: undefined,
                buildingName: undefined,
                outsource: null,

            },
            // 表单参数
            form: {
                gender: '男',
                outsource: '否',
                floor: 1
            },
            // 表单校验
            rules: {
                id: [
                    { required: true, message: "不能为空", trigger: "blur" }
                ],
                dormitoryId: [
                    { required: true, message: "宿舍编号不能为空", trigger: "blur" }
                ],
                buildingName: [
                    { required: true, message: "楼栋名称不能为空", trigger: "change" }
                ],
                capacity: [
                    { required: true, message: "容纳人数不能为空", trigger: "blur" }
                ],
                floor: [
                    { required: true, message: "楼层必填，且是整数", trigger: "blur" }
                ],
                nature: [
                    { required: true, message: "宿舍性质必选", trigger: "blur" }
                ],
            },
            bedbuttonLoading: false,
            //床位
            bedform: {
                dormitoryId: null,
                bedcode: null,
                status: "空位"
            },
            // 弹出层标题
            bedtitle: "",
            // 是否显示弹出层
            bedopen: false,
            // 导入参数
            upload: {
                // 
                open: false,
                // 
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/business/dormitory/importData"
            },
            rowData: {},
            feeopen: false,
            // 部门树选项
            deptOptions: undefined,
            tooltipisShow: false,
            tooltipStates: [], // Array to store tooltip visibility for each card
            lastClickedIndex: -1, // 记录上一次点击的卡片索引
        };
    },
    created() {
        this.getList();
        this.getDeptTree();
        //this.tooltipStates = Array(this.dormitoryList.length).fill(false);
    },
    watch: {
        'form.dormitoryId': function (newDormitoryId) {
            if (newDormitoryId && /^\d+/.test(newDormitoryId)) {
                // 使用正则表达式提取第一个数字
                const firstDigit = parseInt(newDormitoryId.charAt(0), 10);
                this.form.floor = isNaN(firstDigit) ? null : firstDigit;
            } else {
                this.form.floor = null; // 如果宿舍编号不包含数字，将楼层设为null或其他合适的值
            }
        }
    },
    methods: {
        /** 查询宿舍列表 */
        getList() {
            this.loading = true;
            listDormitory(this.queryParams).then(response => {
                this.dormitoryList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                dormitoryId: undefined,
                buildingNumber: undefined,
                buildingName: undefined,
                capacity: 0,
                currentCapacity: undefined,
                adminId: undefined,
                gender: '男',
                outsource: '否'
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 36,
                dormitoryId: undefined,
                buildingNumber: undefined,
                buildingName: undefined,
            },
                this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加宿舍";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const id = row.id || this.ids
            getDormitory(id).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.title = "修改宿舍";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.id != null) {
                        updateDormitory(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addDormitory(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除宿舍编号为"' + ids + '"的数据项？').then(() => {
                this.loading = true;
                return delDormitory(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/dormitory/export', {
                ...this.queryParams
            }, `dormitory_${new Date().getTime()}.xlsx`)
        },
        bedcancel() {
            this.bedopen = false;
        },
        /** 添加床位 */
        handleaddbed(row) {
            this.bedopen = true;
            this.bedtitle = "添加床位";
            this.bedform.dormitoryId = row.id;
        },
        /** 提交新增床位按钮 */
        submitbedForm() {
            this.$refs["bedform"].validate(valid => {
                if (valid) {
                    this.bedbuttonLoading = true;
                    if (this.bedform.id != null) {
                        updateBeds(this.bedform).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.bedopen = false;
                            this.getList();
                        }).finally(() => {
                            this.bedbuttonLoading = false;
                        });
                    } else {
                        addBeds(this.bedform).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.bedopen = false;
                            this.getList();
                        }).finally(() => {
                            this.bedbuttonLoading = false;
                        });
                    }
                }
            });
        },
        handleDeletebed(row) {
            const ids = row.id;
            this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(() => {
                this.loading = true;
                return delBeds(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        //退宿按钮事件
        handleOutline(row) {
            const ids = row.id;
            this.$modal.confirm('是否确认退舍？').then(() => {
                this.loading = true;
                return clearBed(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("退舍成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        getAccommodationStyle(accommodation) {
            if (accommodation === '空位') {
                return {
                    color: 'green'
                };
            } else {
                return {
                    color: 'red'
                };
            }
        },

        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "导入宿舍";
            this.upload.open = true;
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        handleFee(row) {
            this.rowData = row;
            this.feeopen = true;
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = response.data;
            });
        },

        // 选中触发（第一次回显的时候会触发，清除值的时候会触发, value值为undefined） input事件用于v-model双向绑定组件更新父组件值
        treeSelectInput(value, instanceId) {
            //console.log(value, 'input事件')
            if (value === undefined) {
                this.queryParams.department = null;
            }
            //console.log(this.value, 'this.value -- input') // 这个不需要 延迟
        },
        // 选中触发（清除值的时候不会触发）
        treeSelectChange(raw, instanceId) {
            //console.log(raw, '当前的对象')
            setTimeout(() => { // 如果用到this.value 需要setTimeout延迟一下拿到最新的值
                // console.log(raw.label, 'this.value -- select')
                this.queryParams.department = raw.label;
            })
        },
        toggleTooltip(index) {
            if (this.lastClickedIndex === index) {
                // 如果点击了相同的卡片两次，则隐藏 tooltip
                this.$set(this.tooltipStates, index, false);
                this.lastClickedIndex = -1; // 重置上一次点击的索引
            } else {
                // 将所有卡片的 tooltip 都设为隐藏
                this.tooltipStates = this.tooltipStates.map(() => false);
                // 切换当前点击卡片的 tooltip 显示状态
                this.$set(this.tooltipStates, index, !this.tooltipStates[index]);
                this.lastClickedIndex = index; // 更新上一次点击的索引
            }
        }

    }
};
</script>
<style scoped>
.el-cascader-panel {
    height: 60vh;

    .el-scrollbar__wrap {
        height: 100%;
    }
}

.base-info-box {
    overflow: hidden;
}

.card-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    /* 或 space-between 或 flex-start，根据需要调整 */
}

.card {
    width: 100%;
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-content {
    margin-top: 10px;
    min-height: 200px;
}

.card-footer {

    text-align: right;
    margin-top: -10px;
}
</style>